package com.itcoon.transform.assemble.converter;

import com.itcoon.common.core.enums.CodeEnum;
import com.itcoon.transform.base.exception.AssembleException;

import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Optional;

/**
 * @author Miaoxia Yu
 * @date 2020-11-06
 */
public class IntegerToCodeEnumConverter<E extends  Enum<E>& CodeEnum> implements AssembleConverter<Integer, E> {

    @Override
    public boolean support(Type targetType, Object source) {
        return targetType instanceof Class && ((Class<?>)targetType).isEnum() && CodeEnum.class.isAssignableFrom((Class<?>)targetType) && source.getClass().equals(Integer.class);
    }

    @Override
    public E convert(Type targetType, Integer attribute){
        Class<CodeEnum> codeEnumClass = (Class<CodeEnum>)targetType;
        CodeEnum[] codeEnums = codeEnumClass.getEnumConstants();
        Optional<CodeEnum> optional = Arrays.stream(codeEnums).filter(codeEnum -> codeEnum.value().equals(attribute)).findAny();
        if(!optional.isPresent()){
            throw new AssembleException(String.format("Illegal CodeEnum Value#%s for %s", attribute, targetType.getTypeName()));
        }
        return (E)optional.get();
    }
}
